var express = require('express');
var router = express.Router();
var path = require('path');

var MongoClient = require('mongodb').MongoClient; // 引入mongodbClient客户端连接模块
var DB_CONN_STR = 'mongodb://10.31.155.79:27017/happy'; // 设置连接字符串

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/login',function(req,res,next){
  
   MongoClient.connect(DB_CONN_STR,function(err,db){ // 利用客户端连接模块进行connect连接操作
    if(err){
      console.log(err);
      return;
    }else{ // 如果连接成功，则执行下面代码 
    
      var conn = db.collection('user');
      var email = req.body.email;
      var password = req.body.password;

     var data  = {username:email,password:password};
     conn.find(data).toArray(function(err,results){
       if(err){
         console.log(err)
         return;
       }else{      
        if(results.length>0){ //----------如果账号密码输入正确
          console.log('login success',results[0].email);
          req.session.username = results[0].username;
          res.redirect('/');
        }else{
          res.render('login',{ config:'block' })
          console.log('email or password is not exits,please try again');
        }

         db.close();
       }
     });

        
    }
  })


})



router.post('/register',function(req,res,next){
  MongoClient.connect(DB_CONN_STR,function(err,db){ // 利用客户端连接模块进行connect连接操作
    if(err){
      console.log(err);
      return;
    }else{ // 如果连接成功，则执行下面代码 
    
      var conn = db.collection('user');
      var email = req.body.email;
      var password = req.body.password;

      //判断邮箱账号是否被注册过
      var data  = {email:email};
      conn.find(data).toArray(function(err,results){
        if(err){
          console.log(err)
          return;
        }else{     
          //如果已存在   
          if(results.length>0){
            console.log('此账号被注册过');
            //req.session.email = results[0].email;
            res.render('register',{config:'block'});

          }else{
            console.log('此账号可用');
            conn.save({username:email,password:password},function(err,results){
              //res.send('登录成功，正则跳转登录页。。。')
              res.redirect('/login');                 
            })
          }

          db.close();
        }
      });        
    }
  })

})

module.exports = router;
